#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Blueprint, request, jsonify
from app.models import Agent
from app.core.extensions import db
from sqlalchemy import desc, or_

# 创建蓝图
agents_bp = Blueprint('admin_mp_agents', __name__)


@agents_bp.route('/tree', methods=['GET'])
def get_agent_tree():
    """
    获取代理树状结构
    ---
    返回:
      - code: 0表示成功
      - data: 代理树状结构
    """
    try:
        # 查询所有顶级代理（没有上级的代理）
        root_agents = Agent.query.filter_by(parent_id=None).all()

        # 构建树状结构
        result_tree = []
        for agent in root_agents:
            result_tree.append(build_agent_tree(agent))

        return jsonify({
            "code": 0,
            "data": result_tree
        })
    except Exception as e:
        # 记录错误日志
        print(f"获取代理树结构失败: {str(e)}")
        return jsonify({"code": 500, "message": "获取代理树结构失败"}), 500


def build_agent_tree(agent):
    """构建代理树的递归函数"""
    agent_dict = agent.to_dict()
    agent_dict['children'] = []

    # 递归添加子代理
    for child in agent.children:
        agent_dict['children'].append(build_agent_tree(child))

    return agent_dict


@agents_bp.route('/list', methods=['GET'])
def get_agents_list():
    """
    获取代理列表
    ---
    参数:
      - pageSize: 每页数量，默认20
      - pageNum: 页码，默认1
      - search: 搜索关键词
    返回:
      - code: 0表示成功
      - data: 
        - items: 代理列表
        - total: 总记录数
    """
    # 获取查询参数
    page_size = int(request.args.get('pageSize', 20))
    page_num = int(request.args.get('pageNum', 1))
    search = request.args.get('search', '')

    # 计算分页偏移量
    offset = (page_num - 1) * page_size

    try:
        # 构建查询
        query = Agent.query

        # 关键词搜索
        if search:
            query = query.filter(
                or_(
                    Agent.name.like(f'%{search}%'),
                    Agent.mobile.like(f'%{search}%'),
                    Agent.email.like(f'%{search}%')
                )
            )

        # 获取总记录数
        total = query.count()

        # 分页查询并按创建时间降序排序
        agents = query.order_by(desc(Agent.create_time)).offset(offset).limit(page_size).all()

        # 转换为字典列表
        agent_list = [agent.to_dict() for agent in agents]

        # 构建返回结果
        result = {
            "code": 0,
            "data": {
                "items": agent_list,
                "total": total
            }
        }

        return jsonify(result)

    except Exception as e:
        # 记录错误日志
        print(f"获取代理列表失败: {str(e)}")
        return jsonify({"code": 500, "message": "获取代理列表失败"}), 500


# 注册蓝图
def init_app(app):
    app.register_blueprint(agents_bp, url_prefix='/api/admin/mp/agents')
